//
//  YWKeepWatchLocationRecordDetailTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/4.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWKeepWatchLocationRecordDetailTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIImageView+WebCache.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "UILabel+AttributedText.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWPatrolPointRecord.h"
#import "YWMission.h"
#import "YWHandler.h"
//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWKeepWatchMissionManager.h"
#import "YWMissionManager.h"
#import "YWRuleTableViewCell.h"
#import "YWPostTroubleInfoCell.h"
#import "YWCirculationDetailViewController.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionManager.h"

@interface YWKeepWatchLocationRecordDetailTableViewController ()
@property (nonatomic, strong) UIView* headView;
@property (nonatomic, strong) UIImageView* buildingImageView;
@property (nonatomic, strong) UILabel *buildingLabel;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) UIImageView *locationIV;
@property (nonatomic, strong) UILabel *locationLabel;

//巡更项
@property (nonatomic, strong) NSString* ruleContent;
//报障信息
@property (nonatomic, strong) NSArray* postTroubleArray;

@property (nonatomic, strong) UIView* footView;
@property (nonatomic, strong) UILabel *handlerLabel;
@property (nonatomic, strong) UILabel *resultLabel;
@property (nonatomic, strong) UILabel *noteLabel;
@property (nonatomic, strong) NSMutableArray* recordPictures;
@end

@implementation YWKeepWatchLocationRecordDetailTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"keepWatchRecordDetail", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableHeaderView = self.headView;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    NSArray *troubleIdArray = [[YWMissionManager shareManager] troubleIdArrayWithDetailUniqueTag:_patrolPointRecord.detailUniqueTag];
    NSMutableString* troubleIdString = troubleIdArray.count > 0 ? [NSMutableString string] : nil;
    [troubleIdArray enumerateObjectsUsingBlock:^(NSString* _Nonnull idString, NSUInteger idx, BOOL* _Nonnull stop) {
        if (idx!=0) {
            [troubleIdString appendString:@","];
        }
        [troubleIdString appendString:idString];
    }];
    if (troubleIdString.length) {
        [[YWTroubleMissionManager shareManager] requestTroubleMissionStatus:troubleIdString withComplete:^(bool success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _postTroubleArray = nil;
                [self.tableView reloadData];
            });
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setPatrolPointRecord:(YWPatrolPointRecord *)patrolPointRecord{
    _patrolPointRecord = patrolPointRecord;
    if (patrolPointRecord) {
        //记录的图片
        _recordPictures = [NSMutableArray array];
        if (patrolPointRecord.pictures.count) {
            [_recordPictures addObjectsFromArray:patrolPointRecord.pictures];
        }else{
            [_recordPictures addObjectsFromArray:[[YWKeepWatchMissionManager shareManager]recordPictureWithRecordId:patrolPointRecord.patrolpointRecordId recordType:YWPictureRecordTypePatrol]];
        }
    }
}

- (NSString*)ruleContent{
    if (!_ruleContent) {
        NSMutableArray *patrolLineIds = nil;
        if (self.patrolPointRecord) {
            patrolLineIds = [NSMutableArray array];
            [patrolLineIds addObject:[NSString stringWithFormat:@"%ld",(long)self.patrolPointRecord.patrolLineId]];
        }
        NSArray* noteArray = [[YWKeepWatchMissionManager shareManager] patrolLocationNoteWithLocationId:self.patrolPointRecord.locationId lineIds:patrolLineIds];
        NSMutableString *content = [NSMutableString string];
        [noteArray enumerateObjectsUsingBlock:^(YWPatrolLineLocationRel* _Nonnull locationRel, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString *note = [NSString stringWithFormat:@"%lu.%@", (unsigned long)(idx + 1), locationRel.note ?: NSLocalizedString(@"none", nil)];
            if (idx!=0) {
                [content appendString:@"\n"];
            }
            [content appendString:note];
        }];
        if (content.length==0) {
            [content appendString:NSLocalizedString(@"none", nil)];
        }
        _ruleContent = [NSString stringWithFormat:@"%@",content];
    }
    return _ruleContent;
}

- (NSArray *)postTroubleArray{
    if (!_postTroubleArray) {
        _postTroubleArray = [[NSArray alloc] initWithArray:[[YWMissionManager shareManager] postTroubleArrayWithDetailUniqueTag:_patrolPointRecord.detailUniqueTag]];
    }
    return _postTroubleArray;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return UITableViewAutomaticDimension;//[YWRuleTableViewCell cellHeightOfRuleContent:self.ruleContent];
    }else if (indexPath.section==1){
        return UITableViewAutomaticDimension;//_postTroubleArray.count>0?54:44;;
    }else if (indexPath.section ==2) {
        return self.footView.frame.size.height;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 1 ? (self.postTroubleArray.count?:1) : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWRuleTableViewCell *cell = [YWRuleTableViewCell cellWithTableView:tableView];
        cell.ruleContent = self.ruleContent;
        return cell;
    }else{
        if (indexPath.section==1){
            YWPostTroubleInfoCell *cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
            YWReportTroubleModel *reportTrouble = self.postTroubleArray.count>0?self.postTroubleArray[indexPath.row]:nil;
            cell.reportTrouble = reportTrouble;
            return cell;
        }else {
            static NSString *identifier = @"YWKeepWatchLocationRecordDetailTableViewControllerCellIdentifier";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [cell addSubview:self.footView];
            return cell;
        }
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==1) {
        YWReportTroubleModel * reportTrouble =  _postTroubleArray.count>0?_postTroubleArray[indexPath.row]:nil;
        if (reportTrouble) {
            YWCirculationDetailViewController *circulationInfoVC = [[YWCirculationDetailViewController alloc] init];
            circulationInfoVC.isNotShowHandleButton = YES;
            circulationInfoVC.troubleMissionModel = reportTrouble.troubleMission;
            [self.navigationController pushViewController:circulationInfoVC animated:YES];
        }
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWIKeepWatchLocationRecordDetailTableViewControllerForHeaderInSection";
    
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section==0){
        return NSLocalizedString(@"keepWatchItem", nil);//@"巡更项";
    }else if (section==1){
        return NSLocalizedString(@"postTroubleInfo", nil);//@"报障信息";
    }else if (section==2){
        return NSLocalizedString(@"recordInfo", nil);//@"记录信息";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (UIView*)headView
{
    if (!_headView) {
        UIView* headView = [[UIView alloc] init];
        headView.backgroundColor = [UIColor whiteColor];
        _headView = headView;
        
        NSInteger locationId = self.patrolPointRecord.locationId;
        YWBuilding* building = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
        NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:building.surfacePicture];
        [self.buildingImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"placeholder_buliding"]];
        CGFloat imageSize = kLabelH*2;
        [self.buildingImageView setFrame:CGRectMake(kMarginW, kGapH, imageSize, imageSize)];
        
        self.buildingLabel.text = building.buildingName.length>0?building.buildingName:NSLocalizedString(@"unknowBuilding", nil);
        CGFloat dateLabelW = 100;
        CGFloat buildingW = SCREEN_WIDTH-kMarginW*4-imageSize - dateLabelW;
        [self.buildingLabel setFrame:CGRectMake(CGRectGetMaxX(self.buildingImageView.frame)+kMarginW, kGapH, buildingW, kLabelH)];
        self.dateLabel.text = [YWCommonTool showTime:_patrolPointRecord.patrolTime / 1000 andFormatter:KTimeFormatShortTimeDate];
        [self.dateLabel setFrame:CGRectMake(SCREEN_WIDTH-dateLabelW-kMarginW, kGapH, dateLabelW, kLabelH)];
        [self.locationIV setFrame:CGRectMake(CGRectGetMaxX(self.buildingImageView.frame)+kMarginW, CGRectGetMaxY(self.buildingLabel.frame) + 2.5, 17, 17)];
        
        NSString* position = [[YWBuildingManager shareManager] areaLocationNobuildingWithId:locationId];
        NSString *locationStr = position.length ? position : NSLocalizedString(@"noLocation", nil);
        self.locationLabel.text = locationStr;
        CGFloat locationW = SCREEN_WIDTH - 17 - 3 - kMarginW*3-imageSize;
        CGFloat locationH = [YWCommonTool getHeightOfLabel:self.locationLabel.text andWidth:locationW andFont:self.locationLabel.font andMinHeight:kLabelH];
        [self.locationLabel setFrame:CGRectMake(CGRectGetMaxX(self.locationIV.frame) + 3, CGRectGetMaxY(self.buildingLabel.frame), locationW, locationH)];
        
        [_headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, kGapH*2+kLabelH + locationH)];
    }
    return _headView;
}
- (UIImageView*)buildingImageView
{
    if (!_buildingImageView) {
        UIImageView* buildingImageView = [[UIImageView alloc] init];
        buildingImageView.clipsToBounds = YES;
        buildingImageView.layer.cornerRadius = 22.0;
        _buildingImageView = buildingImageView;
        [self.headView addSubview:_buildingImageView];
    }
    return _buildingImageView;
}
- (UILabel*)buildingLabel
{
    if (!_buildingLabel) {
        UILabel* buildingLabel = [[UILabel alloc] init];
        buildingLabel.font = [UIFont boldSystemFontOfSize:16];
        //        buildingLabel.numberOfLines = 0;
        _buildingLabel = buildingLabel;
        [self.headView addSubview:_buildingLabel];
    }
    return _buildingLabel;
}
-(UILabel *)dateLabel{
    if (!_dateLabel) {
        UILabel* dateLabel = [[UILabel alloc] init];
        dateLabel.font = [UIFont systemFontOfSize:13];;
        dateLabel.textAlignment = NSTextAlignmentRight;
        dateLabel.textColor = [UIColor customTextGrayColor];
        _dateLabel = dateLabel;
        [self.headView addSubview:_dateLabel];
    }
    return _dateLabel;
}
- (UIImageView*)locationIV
{
    if (!_locationIV) {
        UIImageView* locationImageV = [[UIImageView alloc] init];
        locationImageV.image = [UIImage imageNamed:@"common_location"];
        _locationIV = locationImageV;
        [self.headView addSubview:_locationIV];
    }
    return _locationIV;
}

- (UILabel*)locationLabel
{
    if (!_locationLabel) {
        UILabel* locationLabel = [[UILabel alloc] init];
        locationLabel.font = KSmallContentFont;
        locationLabel.textColor = [UIColor customTextGrayColor];
        locationLabel.numberOfLines = 0;
        _locationLabel = locationLabel;
        [self.headView addSubview:_locationLabel];
    }
    return _locationLabel;
}
- (UIView *)footView{
    if (!_footView) {
        _footView = [[UIView alloc] init];
        _footView.backgroundColor = [UIColor whiteColor];
        CGFloat resuleSize = 44;
        CGFloat handleW = SCREEN_WIDTH-kMarginW*3-resuleSize;
        
        [self.handlerLabel setFrame:CGRectMake(kMarginW, kGapH, handleW, kLabelH)];
        //结果
        [self.resultLabel setFrame:CGRectMake(SCREEN_WIDTH-kMarginW-resuleSize, self.handlerLabel.frame.origin.y, resuleSize, resuleSize)];
        //备注
        CGFloat noteHeight = [YWCommonTool getHeightOfLabel:self.noteLabel.text andWidth:handleW andFont:self.noteLabel.font andMinHeight:kLabelH];
        [self.noteLabel setFrame:CGRectMake(kMarginW,  CGRectGetMaxY(self.handlerLabel.frame), handleW, noteHeight)];
        //照片
        CGFloat imageViewH = 0;
        if (_recordPictures.count > 0) {
            YWPhotoView* imageV = [[YWPhotoView alloc] init];
            imageV.canAddPhoto = NO;
            imageV.photosArray = _recordPictures;
            [imageV setFrame:CGRectMake(0, CGRectGetMaxY(self.noteLabel.frame) + kGapH, imageV.frame.size.width, imageV.frame.size.height)];
            [_footView addSubview:imageV];
            imageViewH = imageV.frame.size.height+kGapH*2;
        }
        [_footView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, kLabelH+noteHeight+imageViewH+kGapH*2)];
    }
    return _footView;
}

-(UILabel *)handlerLabel{
    if (!_handlerLabel) {
        UILabel* handlerLabel = [[UILabel alloc] init];
        handlerLabel.font = kContentFont;
        handlerLabel.textColor = [UIColor customTextGrayColor];
        NSString *handlerName = _patrolPointRecord.executor.userName.length > 0 ? _patrolPointRecord.executor.userName : NSLocalizedString(@"none", nil);
        [handlerLabel labelText:NSLocalizedString(@"executorFormatter", nil) withAttributedText:handlerName andAttributedColor:[UIColor blackColor]];
        [self.footView addSubview:handlerLabel];
        _handlerLabel = handlerLabel;
    }
    return _handlerLabel;
}
-(UILabel *)resultLabel{
    if (!_resultLabel) {
        UILabel* resultLabel = [[UILabel alloc] init];
        resultLabel.font = kContentFont;
        if (_patrolPointRecord.status == YWPatrolpointRecordStatusTrouble) {
            resultLabel.text = NSLocalizedString(@"unnormal", nil);
            resultLabel.backgroundColor = [UIColor customRedColor];
        }else{
            resultLabel.text = NSLocalizedString(@"normal", nil);
            resultLabel.backgroundColor = [UIColor customGreenColor];
        }
        resultLabel.textColor = [UIColor whiteColor];
        resultLabel.textAlignment = NSTextAlignmentCenter;
        resultLabel.clipsToBounds = YES;
        resultLabel.layer.cornerRadius = 44/2;
        [self.footView addSubview:resultLabel];
        _resultLabel = resultLabel;
    }
    return _resultLabel;
}

- (UILabel*)noteLabel
{
    if (!_noteLabel) {
        UILabel* noteLabel = [[UILabel alloc] init];
        noteLabel.font = kContentFont;
        noteLabel.numberOfLines = 0;
        noteLabel.textColor = [UIColor customTextGrayColor];
        NSString* note = _patrolPointRecord.note.length > 0 ? _patrolPointRecord.note : NSLocalizedString(@"noContent", nil);
        [noteLabel labelText:NSLocalizedString(@"noteFormatter", nil) withAttributedText:note andAttributedColor:[UIColor blackColor]];
        [self.footView addSubview:noteLabel];
        _noteLabel = noteLabel;
    }
    return _noteLabel;
}
@end
